package com.qef.com.mmovie.mvp.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.transition.Fade;
import android.transition.Slide;
import android.transition.Visibility;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.CountCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.konifar.fab_transformation.FabTransformation;
import com.orhanobut.logger.Logger;
import com.qef.com.mmovie.App;
import com.qef.com.mmovie.R;
import com.qef.com.mmovie.api.NetApi;
import com.qef.com.mmovie.api.VideoListBean;
import com.qef.com.mmovie.base.ActivityComponent;
import com.qef.com.mmovie.base.BaseActivity;
import com.qef.com.mmovie.entity.DataBean;
import com.qef.com.mmovie.entity.ItemListBean;
import com.qef.com.mmovie.entity.User;
import com.qef.com.mmovie.img.ImageLoader;
import com.qef.com.mmovie.mvp.adapter.CommentAdapter;
import com.qef.com.mmovie.presenter.VideoHomePresenter;
import com.qef.com.mmovie.presenter.contract.VideoHomeContract;
import com.qef.com.mmovie.utils.AnimatiorUtils;
import com.qef.com.mmovie.utils.Constants;
import com.qef.com.mmovie.utils.DateUtil;
import com.qef.com.mmovie.utils.HindToolbar;
import com.qef.com.mmovie.utils.PopCreator;
import com.qef.com.mmovie.utils.PopWindowUtils;
import com.qef.com.mmovie.utils.ShareUtils;
import com.qef.com.mmovie.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

/**
 * Created by guangjiego on 2017/6/9.
 */

public class VideoDetailActivity extends BaseActivity<VideoHomePresenter> implements VideoHomeContract.View, Toolbar.OnMenuItemClickListener, View.OnClickListener {

    ImageView mImgDetail;
    Toolbar mToolbar;
    ImageView bgImage;
    TextView title;
    TextView type;
    TextView description;
    FloatingActionButton mFab;

    private int commentCount;
    private DataBean dataBean;
    private CollapsingToolbarLayout collToolBar;
    private JCVideoPlayerStandard mVideoPlayer;
    private RecyclerView rcCommon;
    private LinearLayout mView;
    int bgcolor;
    private List<AVObject> commontDatas;
    private TextView mTvCommentCount;
    public static final String VIDEO_INFOS = "video_info";

    @Override
    protected int getLayoutId() {
        return R.layout.video_home_detail_fragment;
    }

    @Override
    protected void initEventAndData() {
        dataBean = (DataBean) getIntent().getExtras().get(VIDEO_INFOS);
        initView();
        initData();

    }

    @Override
    protected void initInject(ActivityComponent activityComponent) {
        activityComponent.inject(this);
    }


    @SuppressLint("CutPasteId")
    private void initView() {
        HindToolbar.setHintWindowTitle(getWindow());
        mView = (LinearLayout) findViewById(R.id.ll_comment);
        mTvCommentCount = (TextView) findViewById(R.id.tv_comment_count);
        mToolbar = ((Toolbar) findViewById(R.id.toolbar));
        mToolbar.setOnMenuItemClickListener(this);
        collToolBar = ((CollapsingToolbarLayout) findViewById(R.id.toolbar_layout));
        mImgDetail = (ImageView) findViewById(R.id.img_detail);
        bgImage = (ImageView) findViewById(R.id.bg_image);
        title = (TextView) findViewById(R.id.titlex);
        type = (TextView) findViewById(R.id.type);
        description = (TextView) findViewById(R.id.description);
        mFab = (FloatingActionButton) findViewById(R.id.fab);
        mVideoPlayer = (JCVideoPlayerStandard) findViewById(R.id.videoplayer);
        View btsheet = findViewById(R.id.design_bottom_sheet);
        mFab.setBackgroundTintList(new ColorStateList(new int[][]{new int[0]}, new int[]{0xffffcc00}));

        mToolbar.setTitle("");
        initToolbarNav(mToolbar);
        ImageLoader.loadAll(this, dataBean.getCover().getDetail(), mImgDetail);
        ImageLoader.loadAll(this, dataBean.getCover().getBlurred(), bgImage);
        title.setText(dataBean.getTitle());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("#").append(dataBean.getCategory())
                .append(" ")
                .append(" / ")
                .append(" ")
                .append(DateUtil.formatTime2(dataBean.getDuration()));
        type.setText(stringBuilder.toString());
        description.setText(dataBean.getDescription());

        mFab.setOnClickListener(v -> {
            if (mFab.getVisibility() == View.VISIBLE) {
                FabTransformation.with(mFab).setListener(new FabTransformation.OnTransformListener() {
                    @Override
                    public void onStartTransform() {
                    }

                    @Override
                    public void onEndTransform() {
                        mVideoPlayer.setUp(dataBean.getPlayUrl(), JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
//                        mVideoPlayer.setUp(dataBean.getPlayUrl(), JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
                        ImageView c = mVideoPlayer.thumbImageView;
                        ImageLoader.getInstance().displayLongImage(dataBean.getCover().getDetail(), App.getInstance(), c);
                        mVideoPlayer.setVisibility(View.VISIBLE);
                        mImgDetail.setVisibility(View.GONE);
                        mVideoPlayer.startVideo();
//                        JumpUtils.goToVideoPlayer(getActivity(), mImgDetail, dataBean);
                    }
                }).

                        transformTo(mImgDetail);
            }
        });

        initColor();
        setViewAnimator();
//        setupWindowAnimations();
        findViewById(R.id.bt_comment).setOnClickListener(this);
        initData();
    }

    private void setupWindowAnimations() {
        Visibility enterTransition = buildEnterTransition();
        getWindow().setEnterTransition(enterTransition);
    }

    private Visibility buildEnterTransition() {
        Fade enterTransition = new Fade();
        enterTransition.setDuration(500);
        // This view will not be affected by enter transition animation
        enterTransition.excludeTarget(R.id.img_detail, true);
        return enterTransition;
    }

    private Visibility buildReturnTransition() {
        Visibility enterTransition = new Slide();
        enterTransition.setDuration(500);
        return enterTransition;
    }

    private void initToolbarNav(Toolbar mToolbar) {
        mToolbar.setNavigationIcon(R.mipmap.ic_arrow_back_white_24dp);
        mToolbar.setNavigationOnClickListener(v -> {
//            this.finish();
//            Visibility returnTransition = buildReturnTransition();
//            getWindow().setReturnTransition(returnTransition);
            finishAfterTransition();
        });
        mToolbar.inflateMenu(R.menu.video_menu);
    }

    private void initData() {
        getCommentCount();
    }

    private void getCommentCount() {
        NetApi.getCommentCount(dataBean.getId(), new CountCallback() {
            @Override
            public void done(int i, AVException e) {
                commentCount = i;
                mTvCommentCount.setText(String.valueOf(i));
            }
        });
    }


    int color = 0xffffcc00;

    private void initColor() {

        Glide.with(this).load(dataBean.getCover().getBlurred()).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                Palette.from(resource).generate(palette -> {
                    try {
                        color = palette.getDarkMutedSwatch().getRgb();
                    } catch (Exception e) {
//                        LogUtil.d(e.getMessage());
                    }
                    collToolBar.setContentScrimColor(color);
                    mFab.setBackgroundTintList(new ColorStateList(new int[][]{new int[0]}, new int[]{color}));

                });

            }
        });
    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        FabTransformation.with(mFab).setListener(new FabTransformation.OnTransformListener() {
//            @Override
//            public void onStartTransform() {
//            }
//
//            @Override
//            public void onEndTransform() {
//                if (mImgDetail.getVisibility() == View.INVISIBLE) {
//                    mImgDetail.setVisibility(View.VISIBLE);
//                }
//            }
//        }).transformFrom(mImgDetail);
//    }

    @Override
    public void onPause() {
        super.onPause();
        mVideoPlayer.release();

    }

    private void setViewAnimator() {
        AnimatiorUtils.setTextViewAlphAnimator(description);
        AnimatiorUtils.setTextViewAlphAnimator(type);
        AnimatiorUtils.setTextViewAlphAnimator(title);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.collect:
                if (User.isLoginToLogin(this)) {
                    NetApi.collection(dataBean, new SaveCallback() {
                        @Override
                        public void done(AVException e) {
                            ToastUtil.showToast(App.getInstance(), "收藏成功！");
                            mTvCommentCount.setText(String.valueOf(commentCount + 1));
                        }
                    });
                }
                return true;
            case R.id.addx:
                ShareUtils.shareGirl(dataBean.getTitle(), dataBean.getPlayUrl(), this);
//                ToastUtil.showToast(App.getInstance(), "分享按钮");
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_comment:
                actionComment();
                break;
        }
    }

    private void actionComment() {
        PopWindowUtils.with(this).loadLayout(R.layout.commentlayout).initPopWindow().setOnCustomListener(new PopCreator.PopCustomkListener() {
            CommentAdapter commAdapter;

            @Override
            public void onCustom(View view, PopupWindow popupWindow) {
                popupWindow.setOutsideTouchable(false);
                popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
                popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                rcCommon = (RecyclerView) view.findViewById(R.id.rc_comment);
                EditText commonEdit = (EditText) view.findViewById(R.id.common_edt);
                if (User.isLogin())
                    ImageLoader.getInstance().displayImage(App.getInstance(), User.getHead().toString(),
                            (ImageView) view.findViewById(R.id.iv_headx), 80, 80);
                view.setBackgroundColor(color);
                rcCommon.setBackgroundColor(color);
                commonEdit.setBackgroundColor(color);
                view.findViewById(R.id.iv_submit).setOnClickListener(view1 -> {
                    if (!User.isLoginToLogin(VideoDetailActivity.this)) {
                        popupWindow.dismiss();
                        openKeyboard();
                        return;
                    }
                    if (commonEdit.getText().toString().length() != 0) {
                        String content = commonEdit.getText().toString().trim();
                        NetApi.comment(dataBean.getId(), content,
                                new SaveCallback() {
                                    @Override
                                    public void done(AVException e) {
                                        ToastUtil.showToast(App.getInstance(), "评论成功！");
                                        getCommentData();
                                        commonEdit.setText("");
                                        openKeyboard();
                                        //添加到我的评论接口
                                        NetApi.addMyCommentInfo(dataBean, content, Constants.Collection.VIDEO_1);
                                    }
                                });
                    } else {
                        ToastUtil.showToast(App.getInstance(), "评论内容不能为空！");
                    }
                });
                LinearLayoutManager layout = new LinearLayoutManager(App.getInstance(), LinearLayoutManager.VERTICAL, false);
                rcCommon.setLayoutManager(layout);
                commontDatas = new ArrayList<>();
                rcCommon.setAdapter(commAdapter = new CommentAdapter(App.getInstance(), commontDatas));
                getCommentData();
            }

            private void getCommentData() {
                commontDatas.clear();
                commAdapter.clear();
                NetApi.getComment(dataBean.getId(), new FindCallback() {
                    @Override
                    public void done(List list, AVException e) {
                        Logger.i(list.toString());
                        commontDatas.addAll(list);
                        commAdapter.addAll(list);
                    }
                });
            }

        }).ShowAsDropDown(mView, 100, 0, 0);
    }

    /**
     * 软键盘隐藏，显示则隐藏 反正显示
     */
    private void openKeyboard() {
        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    public void showContent(VideoListBean videoListBean) {

    }

    @Override
    public void error(Throwable throwable) {

    }
}
